//
//  DataContrller.m
//  TestDemo
//
//  Created by 崔璨 on 2017/9/25.
//  Copyright © 2017年 cccc. All rights reserved.
//

#import "DataContrller.h"
#import "CommonFunc.h"
@implementation DataContrller

#pragma mark - POST请求

+(void)PostRequestUrl:(NSString *)urlStr
                Param:(NSDictionary *)paramDic
       requestSuccess:(successBackBlock)requestSuccessBackBlock
          requestFail:(failBackBlock)requestFailBackBlock
{
    NSDictionary *body = paramDic;
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlStr parameters:nil error:nil];
    
    req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
    
    [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    NSString * str = [NSString stringWithFormat:@"%@:%@",KBasicAuthName,KBasicAuthPassWord];
    //进行加密  [str base64EncodedString]使用开源Base64.h分类文件加密
    NSString * str2 = [NSString stringWithFormat:@"Basic %@",[CommonFunc base64StringFromText:str]];
    [req setValue:str2 forHTTPHeaderField:@"Authorization"];
    
    [req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    
    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        if (!error) {
            
            NSLog(@"Reply JSON: %@", responseObject);
            
            
//            NSDictionary *backDic = responseObject;
            
            if (requestSuccessBackBlock) {
                requestSuccessBackBlock(responseObject);
            }
            
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                
                //blah blah
                
            }
            
        } else {
            if (requestFailBackBlock) {
                requestFailBackBlock([error localizedDescription]);
            }
            NSLog(@"Error: %@, %@, %@", error, response, responseObject);
            
        }
        
    }] resume];
    
    
    
    
    
    
    
    
    
    
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//
//    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//
////    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
//
//    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlStr parameters:nil error:nil];
//
//    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:paramDic options:0 error:nil];
//
//    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//
//    [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//
//    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
//
//    [req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
//
//
//
//    NSData *baseAuth = [[NSString stringWithFormat:@"%@:%@",KBasicAuthName,KBasicAuthPassWord]dataUsingEncoding:NSUTF8StringEncoding];
//    NSString *base64Auth = [baseAuth base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0];
//    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Basic %@",base64Auth] forHTTPHeaderField:kBasicAuthHeader];
//
//
//    [manager POST:urlStr parameters:paramDic constructingBodyWithBlock:^(id _Nonnull formData) {
//    } progress:^(NSProgress * _Nonnull uploadProgress) {
//
//    }
//          success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
//
//
//
//          }
//          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//
//
//
//          }];
}

#pragma mark - Get请求

+(void)GetRequestUrl:(NSString *)urlStr
               Param:(NSDictionary *)paramDic
      requestSuccess:(successBackBlock)requestSuccessBackBlock
         requestFail:(failBackBlock)requestFailBackBlock
{
    
    NSDictionary *body = paramDic;
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:urlStr parameters:nil error:nil];
    
    req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
    
    [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
    NSString * str = [NSString stringWithFormat:@"%@:%@",KBasicAuthName,KBasicAuthPassWord];
    //进行加密  [str base64EncodedString]使用开源Base64.h分类文件加密
    NSString * str2 = [NSString stringWithFormat:@"Basic %@",[CommonFunc base64StringFromText:str]];
    [req setValue:str2 forHTTPHeaderField:@"Authorization"];
    
    [req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:urlStr parameters:paramDic progress:nil success:^(NSURLSessionTask *task, id responseObject) {
        if (requestSuccessBackBlock) {
            requestSuccessBackBlock(responseObject);
        }
        
    } failure:^(NSURLSessionTask *operation, NSError *error) {
        
        if (requestFailBackBlock) {
            requestFailBackBlock([error localizedDescription]);
        }
    }];
    
}

#pragma mark - 上传图片

+(void)uploadImageUrl:(NSString *)urlStr
             andImage:(UIImage *)image
         andImageName:(NSString *)imageNameStr
             andParam:(NSDictionary *)paramDic
       uploadProgress:(uploadProgress)ProgresBackBlock
        uploadSuccess:(successBackBlock)uploadSuccessBackBlock
           uploadFail:(failBackBlock)uploadFailBackBlock
{
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:urlStr parameters:paramDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *data = UIImagePNGRepresentation(image);
        NSString *fileName = imageNameStr;
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"%f",1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        dispatch_async(dispatch_get_main_queue(), ^{
            if (ProgresBackBlock) {
                ProgresBackBlock(1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
            }
        });
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //上传成功
        if (uploadSuccessBackBlock) {
            uploadSuccessBackBlock(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //上传失败
        if (uploadFailBackBlock) {
            uploadFailBackBlock([error localizedDescription]);
        }
    }];
    
   
}


@end
